//
//  LSZPlayThemeVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2017/9/21.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LSZPlayThemeVC.h"
#import "LSZPlayThemeVC+LCAVPlay.h"
#import "JKSongsMessStatus.h"
#import "NetworkTool+LCAVPlay.h"

@interface LSZPlayThemeVC ()
{
    NSInteger lastClickRow;
}
@end

@implementation LSZPlayThemeVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.numberPage = 1;
    [self QueryTheCachePastorIsSermonAudioClassificationPlayData :self.numberPage];
    [LCFloatingWindow sharedInstance].hidden = NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [LCFloatingWindow sharedInstance].hidden = YES;
    if(self.viewSharePopover.hidden == NO){
        self.viewSharePopover.hidden = YES;
        self.viewLow.hidden = YES;
        self.butCancel.hidden = YES;
    }
}
-(NSMutableArray *)mutAllOriginalArrayData
{
    if (_mutAllOriginalArrayData == nil) {
        _mutAllOriginalArrayData = [[NSMutableArray alloc]init];
    }
    return _mutAllOriginalArrayData;
}
#pragma mark - 查看是否有缓存信息
-(void)QueryTheCachePastorIsSermonAudioClassificationPlayData :(NSInteger)number
{
    //jiangdao_yinpin_play
    __weak typeof(self) weakSelf = self;

    NSString * StrFile = [NSString stringWithFormat:@"%@_%@_%@",jiangdao_yinpin_play,self.titleStr,weakSelf.parentId];
    [LSZCacheHandling initWithfindPlist:StrFile :^(BOOL isOk, NSDictionary * dic) {
        if (isOk == YES) {
            LSZPriestPreachedAudioManager * MG  = [[LSZPriestPreachedAudioManager alloc]initWithDicPriestPreachedAudioManager:dic type:self.typeStr value:@"2"];
            [weakSelf.mutArrayData removeAllObjects];
            [weakSelf.mutArrayData addObjectsFromArray:MG.mutDataArray];
            
            [weakSelf.mutAllOriginalArrayData removeAllObjects];
            [weakSelf.mutAllOriginalArrayData setArray:MG.historyArrayData];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [weakSelf.tableviewPlay reloadData];
            }];
        }else{
            [self PlayThemeData:number];
        }
    }];
}
#pragma mark - 请求的数据
-(void)PlayThemeData :(NSInteger)number
{
     __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic initWithThemeAlbum:[NSString stringWithFormat:@"%ld",(long)number] type:weakSelf.typeStr opt:weakSelf.optStr parentId:weakSelf.parentId value:@"2" titleStr:self.titleStr:^(BOOL isOk, NSString * str, LSZPriestPreachedAudioManager * AudioManager) {
        if (isOk == YES) {
            if (number == 1) {
                [weakSelf.mutArrayData removeAllObjects];
                [weakSelf.mutArrayData addObjectsFromArray:AudioManager.mutDataArray];
                
                [weakSelf.mutAllOriginalArrayData removeAllObjects];
                [weakSelf.mutAllOriginalArrayData setArray:AudioManager.historyArrayData];
            }else{
                [weakSelf.mutArrayData addObjectsFromArray:AudioManager.mutDataArray];
                [weakSelf.mutAllOriginalArrayData addObjectsFromArray:AudioManager.historyArrayData];
            }
            NSString * distinguishValue =  [LSZSpecialPackaging addPlaylistWithArrayData:weakSelf.mutAllOriginalArrayData];
            NSString * strRow = [[NSString alloc]init];
            if([self.lastClassNumberRow isEqualToString:@"2"]){
                strRow = [NSString stringWithFormat:@"6_2_%@",self.lastPageNumberRow];
            }
            if([self.lastClassNumberRow isEqualToString:@"3"]){
                strRow = [NSString stringWithFormat:@"6_3_%@",self.lastPageNumberRow];
            }
            if([self.lastClassNumberRow isEqualToString:@"4"]){
                  strRow = [NSString stringWithFormat:@"6_4_%@",self.lastPageNumberRow];
            }
            if ([distinguishValue isEqualToString:strRow]) {
                LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
                _LCPlayer.songs = playlistTest.allSongs;
            }
            [weakSelf.tableviewPlay  reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",str]];
            [SVProgressHUD dismissWithDelay:1];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creareAVPlay];
    
    self.title = [NSString stringWithFormat:@"%@",self.titleStr];
    [self.tableviewPlay registerClass:[LSZAudioFrequencyTableViewCell class] forCellReuseIdentifier:@"LSZAudioFrequencyTableViewCell"];
    
    [self.tableviewPlay registerClass:[LSZRandombroadcastHeaderCell class] forHeaderFooterViewReuseIdentifier:@"LSZRandombroadcastHeaderCell"];
    self.mutArrayData = [[NSMutableArray alloc]init];
    self.tableviewPlay.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 进入刷新状态后会自动调用这个block
            self.numberPage = 1;
            //赞美诗的分类
            [self QueryTheCachePastorIsSermonAudioClassificationPlayData:self.numberPage];
            [self.tableviewPlay.mj_header endRefreshing];
        });
    }];
    // 上拉刷新
    self.tableviewPlay.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 进入刷新状态后会自动调用这个block
            self.numberPage++;
            //赞美诗的分类
            [self PlayThemeData:self.numberPage];
            [self.tableviewPlay.mj_footer endRefreshing];
        });
    }];
    self.numberRow = -1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mutArrayData.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LSZRandombroadcastHeaderCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZRandombroadcastHeaderCell"];
    if (!cell) {
        cell = [[LSZRandombroadcastHeaderCell alloc]initWithReuseIdentifier:@"LSZRandombroadcastHeaderCell"];
    }
    UITapGestureRecognizer * singleTapimageView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickButRandom:)];
    [cell.imageViewPlay addGestureRecognizer:singleTapimageView];
    
    UITapGestureRecognizer * singleTaplabel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickButRandom:)];
    [cell.label addGestureRecognizer:singleTaplabel];
    
    [cell.butPaly addTarget:self action:@selector(clickButRandom:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZAudioFrequencyTableViewCell * cell = [[LSZAudioFrequencyTableViewCell alloc]initWithNumberAudioFrequency:1];
    LSZPriestPreachedAudioMg * audioMg = nil;
    audioMg = self.mutArrayData[indexPath.row];
    cell.labelNumber.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    [cell.imageViewAudio                                 sd_setImageWithURL:[NSURL URLWithString:audioMg.image] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cell.imageViewHook.image = [UIImage imageNamed:@"placeholder"];
    cell.labelTitle.text = [NSString stringWithFormat:@"%@",audioMg.title];
    cell.labelChapters.text = [NSString stringWithFormat:@"%@",audioMg.album];
    cell.butShare.tag = indexPath.row;
    [cell.butShare addTarget:self action:@selector(clickButShare:) forControlEvents:UIControlEventTouchUpInside];
    if (_LCPlayer.selectedIndex == indexPath.row && [[LCHistoryDataManager loadOneSongsData] isEqualToString:cell.labelTitle.text] && [cell.labelChapters.text isEqualToString:_LCPlayer.playingSong.album]) {
        [cell clickOnThisSongToPlay:YES];
        lastClickRow = indexPath.row;
    }else{
        [cell clickOnThisSongToPlay:NO];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LCPlaylist *playlist = [LCPlaylist new];
    for (NSInteger i = 0; i < self.mutArrayData.count; i++) {
        LSZPriestPreachedAudioMg *audioMg = nil;
        audioMg = self.mutArrayData[i];
        NSDictionary *json = [audioMg yy_modelToJSONObject];
        JKSongsMessStatus *songDictionary = [JKSongsMessStatus yy_modelWithJSON:json];
        [playlist addSong:songDictionary];
    }
    [_PlaylistMgr removeAllPlaylists];
    [_PlaylistMgr addPlaylist:playlist];
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    [_LCPlayer playAtIndex:indexPath.row isSelectPlay:YES];//播放歌曲
}
#pragma mark - 随机播放按钮的点击事件
-(void)clickButRandom:(UIButton *)but
{
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    _LCPlayer.listStatus = LCMusicListStatusAllCycle;
    [_LCPlayer playAtIndex:0 isSelectPlay:YES];
}
#pragma mark - 分享弹出来的view
-(UIView *)viewSharePopover
{
    if(_viewSharePopover == nil){
        [LSZSpecialPackaging initAlterView:self.view :^(UIView * viewBack,UIView * viewLow, UIButton * buttonFriends, UIButton * buttonFriendsCircle, UIButton * buttonDownload, UIButton * butCancel) {
            _viewSharePopover = viewBack;
            [self.view bringSubviewToFront:_viewSharePopover];
            [self.tableviewPlay bringSubviewToFront:_viewSharePopover];
            
            
            self.viewLow = viewLow;
            [self.view bringSubviewToFront:self.viewLow];
            [self.tableviewPlay bringSubviewToFront:self.viewLow];
            
            self.butCancel = butCancel;
            [self.view bringSubviewToFront:self.butCancel];
            [self.tableviewPlay bringSubviewToFront:self.butCancel];
            
            [buttonFriends addTarget:self action:@selector(clickShareWeiXin) forControlEvents:UIControlEventTouchUpInside];
            [buttonFriendsCircle addTarget:self action:@selector(clickShareWeiXinFriendsCircle) forControlEvents:UIControlEventTouchUpInside];
            [buttonDownload addTarget:self action:@selector(clickDoenload) forControlEvents:UIControlEventTouchUpInside];
            [butCancel addTarget:self action:@selector(clickButCancel) forControlEvents:UIControlEventTouchUpInside];
        }];
    }
    return _viewSharePopover;
}
#pragma mark - 点击的哪一行的要分享
-(void)clickButShare :(UIButton *)but
{
    self.shareAndDownloadNumberRow = but.tag;
    
    if(self.numberRow == but.tag){
        self.viewSharePopover.hidden = YES;
        self.viewLow.hidden = YES;
        self.butCancel.hidden = YES;
        [LCFloatingWindow sharedInstance].hidden = NO;
        self.numberRow = -1;
    }else{
        self.viewSharePopover.hidden = NO;
        self.viewLow.hidden = NO;
        self.butCancel.hidden = NO;
        [LCFloatingWindow sharedInstance].hidden = YES;
        self.numberRow = but.tag;
    }
}
#pragma mark - 点击微信分享好友
-(void)clickShareWeiXin
{
    NSLog(@"点击微信分享好友");
    NSString * strUrl = [[NSString alloc]init];
    NSString * strTitle = [[NSString alloc]init];
    LSZPriestPreachedAudioMg * audioMg = nil;
    audioMg = self.mutArrayData[self.shareAndDownloadNumberRow];
    
    NSArray* imageArray = @[[UIImage imageNamed:@"placeholder"]];
    strUrl = audioMg.fileUrl;
    strTitle = audioMg.title;
    [LSZSpecialPackaging shareWXWithViewController:self imageArray:imageArray url:strUrl title:strTitle contentMessage:@"" type:0];
    [self clickButCancel];
}
#pragma mark - 点击微信分享朋友圈
-(void)clickShareWeiXinFriendsCircle
{
    NSLog(@"点击微信分享朋友圈");
    NSString * strUrl = [[NSString alloc]init];
    NSString * strTitle = [[NSString alloc]init];
    LSZPriestPreachedAudioMg * audioMg = nil;
    audioMg = self.mutArrayData[self.shareAndDownloadNumberRow];
    NSArray* imageArray = @[[UIImage imageNamed:@"placeholder"]];
    strUrl = audioMg.fileUrl;
    strTitle = audioMg.title;
    [LSZSpecialPackaging shareWXWithViewController:self imageArray:imageArray url:strUrl title:strTitle contentMessage:@"" type:1];
    [self clickButCancel];
}
#pragma mark - 点击下载的按钮
-(void)clickDoenload
{
    LSZPriestPreachedAudioMg * audioMg = nil;
    audioMg = self.mutArrayData[self.shareAndDownloadNumberRow];
    NSDictionary *json = [audioMg yy_modelToJSONObject];
    JKSongsMessStatus *song = [JKSongsMessStatus yy_modelWithJSON:json];
    [kNetworkTool downloadSongWithUrl:song];
    [self clickButCancel];
    NSLog(@"点击下载的按钮的点击事件");
}
#pragma mark - 分享或者下载的view   下落
-(void)clickButCancel
{
    _viewSharePopover.hidden = YES;
    self.viewLow.hidden = YES;
    self.butCancel.hidden = YES;
    [LCFloatingWindow sharedInstance].hidden = NO;
    self.numberRow = -1;
}

-(UITableView *)tableviewPlay
{
    if (_tableviewPlay == nil) {
        _tableviewPlay  = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-60-HOME_INDICATOR_HEIGHT) style:UITableViewStylePlain];
        _tableviewPlay.delegate = self;
        _tableviewPlay.dataSource = self;
        //添加以下代码关闭估算行高
        _tableviewPlay.estimatedRowHeight = 0;
        _tableviewPlay.estimatedSectionHeaderHeight = 0;
        _tableviewPlay.estimatedSectionFooterHeight = 0;
        [self.view addSubview:_tableviewPlay];
    }
    return _tableviewPlay;
}
@end
